from handler_helpers.base_handler_helper import BaseHandlerHelper
from utils.check_params_utlil import CheckParams


class EditHandlerHelper(BaseHandlerHelper):

    def _get_no_update_field(self):
        no_update_field_list = ["id", "guid", "create_user_id", "create_time", "last_update_user_id",
                                "last_update_time", "is_delete"]
        if hasattr(self.cls(), "get_no_update_field"):
            return set(no_update_field_list + getattr(self.cls(), "get_no_update_field"))
        return no_update_field_list

    def _get_edit_info(self, conditions):
        """
        即使在add_edit_params中存在的数据项，如果此时也在get_no_update_field中进行了配置，那么同样不会更新，也不会触发字段检查
        """
        edit_conditions = []
        _no_u_f_list = self._get_no_update_field()
        for con in conditions:
            if con[0] not in _no_u_f_list:
                edit_conditions.append(con)
        return edit_conditions

    def edit_handler(self):
        if not self.request.request_data.get("guid"):
            return self._failure_response(message="编辑接口需要传递guid")
        guid = self.request.request_data['guid']
        conditions = self._get_conditions
        # 获取可以修改的字段
        edit_conditions = self._get_edit_info(conditions)
        check_r = CheckParams(params=self.request.request_data,
                              conditions=edit_conditions).check()

        if not check_r.is_success:
            return self._failure_response(message=check_r.message)
        data = check_r.data
        res = self.bll_cls(request=self.request, cls=self.cls, unique_fields=self._get_unique_fields). \
            join_edit(guid, **data)
        return self._response(res)
